import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @Author: tgy
 * @Date: 2020-07-29 11:09
 */

class MyCallable implements Callable<Integer> {


    @Override
    public Integer call() throws Exception {

        TimeUnit.SECONDS.sleep(2);
        return 1024;
    }
}

public class CallableTest {

    public static void main(String[] args) throws Exception{

        FutureTask<Integer> integerFutureTask = new FutureTask<>(new MyCallable());

        new Thread(integerFutureTask).start();

        while (!integerFutureTask.isDone()){

            System.out.println("----");
        }

        // get()方法会阻塞线程，直到call方法执行返回拿到结果，再继续往下执行
        integerFutureTask.get();

        try {

            integerFutureTask.get(2,TimeUnit.SECONDS);

        }catch (TimeoutException e){

            e.printStackTrace();
        }

        System.out.println(integerFutureTask.get());
    }
}
